import { FetchAPI, PageParams, Pager, UserPermission, UserPermissionService } from '../../interface'
import { Db, Filter } from 'mongodb'

export class UserPermissionServiceImpl implements UserPermissionService {
    public CONN_NAME = 'rbac_permission';
    private db: Db
    constructor(db: Db) {
        this.db = db
    }
    permissionCreate: FetchAPI<UserPermission[]> = async (permissions) => {
        const keys: string[] = []
        const key_set = new Set(permissions.map(p => {
            keys.push(p.key)
            return p.key
        }))
        if (key_set.size !== keys.length) {
            return {
                success: false,
                error: '权限重复',
            }
        }
        const conn = this.db.collection<UserPermission>(this.CONN_NAME)
        const exist = await conn.find({ key: { $in: keys } }).toArray()
        if (exist.length) {
            return {
                success: false,
                error: '权限重复',
            }
        }
        await conn.insertMany(permissions)
        return {
            success: true,
        }
    }
    permissionDelete: FetchAPI<string[]> = async (keys) => {
        const conn = this.db.collection<UserPermission>(this.CONN_NAME)
        await conn.deleteMany({ key: { $in: keys } })
        return {
            success: true,
        }
    }
    permissionUpdate: FetchAPI<Partial<UserPermission> & { key: UserPermission['key'] }> = async (permission) => {
        const conn = this.db.collection<UserPermission>(this.CONN_NAME)
        await conn.updateOne({ key: permission.key }, { $set: permission })
        return {
            success: true,
        }
    }
    permissionList: FetchAPI<PageParams<Partial<UserPermission>>, Pager<UserPermission>> = async (body) => {
        const { page = 1, pageSize = 10, params = {} } = body;
        const offset = (page - 1) * pageSize
        const conn = this.db.collection<UserPermission>(this.CONN_NAME)
        const { key, name, desc } = params
        const filter: Filter<UserPermission> = {}
        if (key) {
            filter.key = key
        }
        if (name) {
            filter.name = { $regex: name, $options: 'i' }
        }
        if (desc) {
            filter.desc = { $regex: desc, $options: 'i' }
        }
        const list = await conn.find(filter).skip(offset).limit(pageSize).toArray()
        return {
            success: true,
            data: {
                list,
                total: await conn.countDocuments(filter),
                page,
                pageSize,
            },
        }
    }
}